<template>
  <div class="select">
    <van-field
      clickable
      readonly
      :is-link="!disabled"
      :label="label"
      :value="selectValue"
      :placeholder="placeholder"
      :required="required"
      :disabled="disabled"
      :rules="rules"
      @click="showPicker = !disabled"
    />
    <SelectPopup
      :showPickerDlg="showPicker"
      :value="value"
      :title="label"
      :multiple="multiple"
      :dataList="dataList"
      :props="{
        text: prop.label,
        value: prop.value
      }"
      :color="color"
      @input="onChange"
      @close="showPicker = false"
    />
  </div>
</template>

<script>
import { findItemFromList } from '@/utils';
import SelectPopup from './SelectPopup/index.vue';

const DEFAULT_PROPS = {
  label: 'name',
  value: 'id'
};

export default {
  name: 'fieldSelect',
  props: {
    value: {
      type: [String, Number, Array]
    },
    label: {
      type: String
    },
    placeholder: {
      type: String
    },
    disabled: {
      type: Boolean,
      default: false
    },
    required: {
      type: Boolean,
      default: false
    },
    rules: {
      type: Array
    },
    // 是否多选
    multiple: {
      type: Boolean,
      default: false
    },
    dataList: {
      type: Array,
      default: () => []
    },
    // 选中颜色
    color: {
      type: String
    },
    prop: {
      type: Object,
      default: () => {
        return {
          ...DEFAULT_PROPS
        }
      }
    }
  },
  components: {
    SelectPopup
  },
  data () {
    return {
      dirty: false,
      showPicker: false
    }
  },
  methods: {
    onChange (value) {
      this.$emit('input', value);
      this.$emit('change', value);
    },
    setDirty (dirty) {
      this.dirty = dirty;
    },
    getDirty () {
      return this.dirty;
    }
  },
  computed: {
    selectValue () {
      if (this.value == null) return '';
      let temp = this.value;
      if (Array.isArray(this.dataList)) {
        if (this.multiple) {
          temp = Array.isArray(this.value) ? this.value.map(item => {
            let node = findItemFromList(this.dataList, item, this.prop.value);
            return node ? node[this.prop.label] : null;
          }).filter(item => item != null) : this.value;
        } else {
          let node = findItemFromList(this.dataList, this.value, this.prop.value);
          if (node) temp = node[this.prop.label];
        }
      }
      return Array.isArray(temp) ? temp.join(' / ') : temp;
    }
  }
}
</script>

<style>
</style>
